package controllers

import (
	"encoding/json"
	"onion/models"
	"onion/utils/crypt"
	"onion/utils/tool"

	"github.com/astaxie/beego/orm"
)

type UserController struct {
	BaseController
}

type RegParam struct {
	Username      string `json:"username"`
	Password      string `json:"password"`
	SuperPassword string `json:"su_pass"`
	MachineCode   string `json:"machine_code"`
}

func (this *UserController) Register() {
	var user RegParam
	var err error
	id, err := this.GetInt("id")
	if err != nil {
		this.ErrorJson(tool.PARAMERR, "参数错误")
		return
	}
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &user); err != nil {
		this.ErrorJson(tool.PARAMERR, "参数错误")
		return
	}
	o := orm.NewOrm()
	v := models.BxUser{}
	s := models.BxSoftware{}
	s.Id = id
	if models.IsBlackMachineCode(user.MachineCode, id) {
		this.ErrorJson(tool.BLACK, "当前机器码为黑名单")
		return
	}
	restrict_time := this.GetTime() - (s.RestrictRegtime * 60 * 60)
	restrict := models.CountReg(v.MachineCode, restrict_time, s.Id)
	if restrict >= s.RestrictRegnum {
		this.ErrorJson(tool.REGERR, "注册上限")
		return
	}
	if err = o.Read(&s); err != nil {
		this.ErrorJson(tool.SOFTWAREERR, "当前应用不存在")
		return
	}
	v.Username = user.Username
	if err = o.Read(&v, "username"); err == nil {
		this.ErrorJson(tool.ACCOUNTERR, "该用户已存在")
		return
	}
	v.Username = user.Username
	v.MachineCode = user.MachineCode
	v.Regtime = this.GetTimeString()
	v.Regip = this.GetIP()
	v.SoftwareId = s.Id
	v.MenberId = 1
	v.Salt = this.RndStr(6)
	v.Password = crypt.MD5String(user.Password + v.Salt)
	v.SuperPassword = crypt.MD5String(user.SuperPassword + v.Salt)
	var reg_log string
	v.Endtime = 0
	if s.GiveTime > 0 {
		v.Endtime = (s.GiveTime * 60) + this.GetTime()
		reg_log = "赠送时间: " + string(rune(s.GiveTime)) + "分钟"
	}
	if _, err = o.Insert(&v); err != nil {
		this.ErrorJson(tool.DBERROR, "注册失败")
		return
	}
	this.Success(reg_log, map[string]interface{}{
		"give_time":   s.GiveTime,
		"password":    user.Password,
		"su_password": user.SuperPassword,
	})
}
